<template>
	<view class="min100 pt-60">
		<view class="text-center mb-60">
			<image :src="info.image" class="orderImg radius-20"></image>
			<view class="gray size-30 mt-40">
				{{info.name}}
			</view>
			<view class="mtb-40 red bold size-36">
				￥{{info.price}}
			</view>
			<!-- <view class="gray mb-60 size-30">
				订单号：{{info.order_num}}
			</view>
			<view class="gray mt-60 size-30">
				下单时间：{{info.create_time}}
			</view> -->
		</view>
		<!-- 支付 -->
		<!-- #ifdef H5 -->
		<view class="plr-30 ptb-30" v-if="isWx==true">
			<view class="text-center gray bold mb-60 size-32">
				请选择支付方式
			</view>
			<radio-group @change="radioChange">
				<label class="flex mb-40 flex-between" v-for="(item, index) in listWx" :key="item.value">
					<view class="flex gray">
						<image src="../../static/balance.png" mode="" class="payIcon mr-20" v-if="index==0"></image>
						<image src="../../static/wx.png" mode="" class="payIcon mr-20" v-if="index==1"></image>
						<image src="../../static/fast.png" mode="" class="payIcon mr-20" v-if="index==2||index==3">
						</image>
						<view>{{item.name}}<text v-if="index==0" class="size-26 red">（{{userAccount}})</text></view>
						<view>
						</view>
					</view>
					<radio :value="item.name" :checked="index === current" color="#44ACFF" />
				</label>
			</radio-group>
		</view>
		<!-- 普通H5环境 -->
		<view class="plr-30 ptb-30" v-if="isWx==false">
			<view class="text-center gray  bold mb-60 size-32">
				请选择支付方式
			</view>
			<radio-group @change="radioChange">
				<label class="flex mb-40 flex-between" v-for="(item, index) in list" :key="item.value">
					<view class="flex gray">
						<image src="../../static/balance.png" v-if="index==0" class="payIcon mr-20"></image>
						<image src="../../static/fast.png" v-else class="payIcon mr-20"></image>
						<view>{{item.name}}<text v-if="index==0" class="size-26 red">（{{userAccount}})</text></view>
						<view>
						</view>
					</view>
					<radio :value="item.name" :checked="index === current" color="#44ACFF" />
				</label>
			</radio-group>
		</view>
		<!-- #endif -->
		<!-- app环境 -->
		<!-- #ifdef APP-PLUS -->
		<view class="plr-30 ptb-30">
			<view class="text-center gray  bold mb-60 size-32">
				请选择支付方式
			</view>
			<radio-group @change="radioChange">
				<label class="flex mb-40 flex-between" v-for="(item, index) in listApp" :key="item.value">
					<view class="flex gray">
						<image src="../../static/balance.png" v-if="index==0" class="payIcon mr-20" mode=""></image>
						<image src="../../static/wx.png" v-if="index==1" class="payIcon mr-20" mode=""></image>
						<image src="../../static/ali.png" v-if="index==2" class="payIcon mr-20" mode=""></image>
						<image src="../../static/ali.png" v-if="index==3||index==4" class="payIcon mr-20" mode="">
						</image>
						<view>{{item.name}}<text v-if="index==0" class="size-26 red">（{{userAccount}})</text></view>
						<view>
						</view>
					</view>
					<radio :value="item.name" :checked="index === current" color="#44ACFF" />
				</label>
			</radio-group>
		</view>
		<!-- #endif -->
		<u-button type="primary" hover-class="none" style="color: #fff!important;" @click="toPay" class="payBtn">确认支付</u-button>
	</view>
</template>

<script>
	// #ifdef H5
	import wx from "weixin-js-sdk";
	// #endif
	export default {
		data() {
			return {
				payType: '余额支付',
				userAccount: 0,
				listApp: [{
						value: '0',
						name: '余额支付'
					},
				],
				listWx: [{
						value: '0',
						name: '余额支付'
					}
				],
				list: [{
						value: '0',
						name: '余额支付'
					}
				],
				current: 0,
				info: {},
				isWx: false,
				btnDisabled: false,
				config_appid: '',
				id: ""
			}
		},
		onLoad(options) {
			this.id = options.order_id;
			this.$http('api/orders/boxOrderDetail', {
				id: this.id
			}).then(res => {
				this.info = res;
			})
		},
		onShow() {
			this.$http('api/account/account').then(res => {
				this.userAccount = res.account;
			})
			this.$http('api/login/serverConfig').then(res => {
				this.config_appid = res.wx_global_app_id;
			})
			// 判断是否为微信环境
			// #ifdef H5
			let ua = navigator.userAgent.toLowerCase();
			let url = window.location.href;
			if (ua.match(/MicroMessenger/i) == "micromessenger") {
				if (url.indexOf("code") != -1) {
					let code = url
						.split("?")[1]
						.split("&")[0]
						.split("=")[1];

					this.$http('api/user/auth', {
						code: code
					}, "POST").then(res => {})
				}
				this.isWx = true;
			} else {
				this.isWx = false;
			}
			// #endif
		},
		methods: {
			radioChange(e) {
				this.payType = e.detail.value;
			},
			toPay() {
				let _this = this;
				if (this.current == -1) {
					uni.showToast({
						title: "请选择支付方式!",
						icon: "none"
					})
					return;
				}
				this.btnDisabled = true;
				// 余额抵扣
				if (this.payType == '余额支付') {
					// H5环境
					this.$http('api/orders/boxPay', {
						id: this.id,
						pay_type: 1
					}).then(res => {
						this.btnDisabled = false;
						this.buyShow = false;
						uni.showToast({
							title: "购买成功!"
						})
						setTimeout(() => {
							uni.navigateTo({
								url: "../my/myBox?current=" + 0 + "&status=" + 0
							})
						}, 500)
					})
				}
				if (this.payType == '快捷支付一') {
					this.$http('api/orders/boxPay', {
						id: this.id,
						pay_type: 6
					}).then(res => {
						this.btnDisabled = false;
						this.buyShow = false;
						let data = res.pay.postData;
						let url = res.pay.url;
						let postForm = document.createElement("form");
						postForm.method = "post";
						postForm.action = url;
						let charInput = document.createElement("input");
						charInput.setAttribute("name", "charset");
						charInput.setAttribute("value", data.charset);
						postForm.appendChild(charInput);
						let dataInput = document.createElement("input");
						dataInput.setAttribute("name", "data");
						dataInput.setAttribute("value", data.data);
						postForm.appendChild(dataInput);
						let signInput = document.createElement("input");
						signInput.setAttribute("name", "sign");
						signInput.setAttribute("value", data.sign);
						postForm.appendChild(signInput);
						let typeInput = document.createElement("input");
						typeInput.setAttribute("name", "signType");
						typeInput.setAttribute("value", data.signType);
						postForm.appendChild(typeInput);
						document.body.appendChild(postForm);
						postForm.submit();
					})
				}
				if (this.payType == '快捷支付二') {
					this.$http('api/orders/boxPay', {
						id: this.id,
						pay_type: 7
					}).then(res => {
						this.btnDisabled = false;
						this.buyShow = false;
						let data = res.pay.postData;
						let url = res.pay.url;
						let postForm = document.createElement("form");
						postForm.method = "post";
						postForm.action = url;
						let charInput = document.createElement("input");
						charInput.setAttribute("name", "charset");
						charInput.setAttribute("value", data.charset);
						postForm.appendChild(charInput);
						let dataInput = document.createElement("input");
						dataInput.setAttribute("name", "data");
						dataInput.setAttribute("value", data.data);
						postForm.appendChild(dataInput);
						let signInput = document.createElement("input");
						signInput.setAttribute("name", "sign");
						signInput.setAttribute("value", data.sign);
						postForm.appendChild(signInput);
						let typeInput = document.createElement("input");
						typeInput.setAttribute("name", "signType");
						typeInput.setAttribute("value", data.signType);
						postForm.appendChild(typeInput);
						document.body.appendChild(postForm);
						postForm.submit();
					})
				}
				// app环境
				// #ifdef APP-PLUS

				if (this.payType == '微信支付') {
					this.$http('api/orders/boxPay', {
						id: this.id,
						pay_type: 3
					}).then(res => {
						// 微信
						uni.requestPayment({
							"provider": "wxpay",
							"orderInfo": {
								"appid": res.pay.appid, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
								"noncestr": res.pay.noncestr, // 随机字符串
								"package": res.pay.package, // 固定值
								"partnerid": res.pay.partnerid, // 微信支付商户号
								"prepayid": res.pay.prepayid, // 统一下单订单号 
								"timestamp": res.pay.timestamp, // 时间戳（单位：秒）
								"sign": res.pay.sign // 签名，这里用的 MD5/RSA 签名
							},
							success(res) {
								_this.buyShow = false;
								uni.showToast({
									title: "购买成功!"
								})
								setTimeout(() => {
									uni.navigateTo({
										url: "../my/myBox?current=" + 0 + "&status=" + 0
									})
								}, 500)
							},
							fail(e) {}
						})
					})
				} else if (this.payType == '支付宝支付') {
					this.$http('api/orders/boxPay', {
						id: this.id,
						pay_type: 4
					}).then(res => {
						console.log(res);
						// 支付宝
						uni.requestPayment({
							provider: 'alipay',
							orderInfo: res.pay, //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
							success: function(res) {
								_this.buyShow = false;
								uni.showToast({
									title: "购买成功!"
								})
								setTimeout(() => {
									uni.navigateTo({
										url: "../my/myBox?current=" + 0 + "&status=" +
											0
									})
								}, 500)
							},
							fail: function(err) {
								console.log('fail:' + JSON.stringify(err));
							}
						});
					})
				}
				// #endif
				// #ifdef H5
				if (this.isWx == true) {
					if (this.payType == '微信支付') {
						let redirect_uri = window.location.href.split("?appid=")[0];
						this.$http('api/user/userInfo').then(res => {
							if (res.is_wx_auth == 0) {
								window.location.href =
									"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
									this.config_appid +
									"&redirect_uri=" +
									encodeURIComponent(redirect_uri) +
									"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
								return;
							}
							this.$http('api/orders/boxPay', {
								id: this.id,
								pay_type: 2
							}).then(res => {
								this.btnDisabled = false;
								// 公众号环境
								wx.config({
									debug: false, // 这里一般在测试阶段先用ture，等打包给后台的时候就改回false,
									appId: res.pay.appId, // 必填，公众号的唯一标识
									timestamp: res.pay.timeStamp, // 必填，生成签名的时间戳
									nonceStr: res.pay.nonceStr, // 必填，生成签名的随机串
									signature: res.pay.paySign, // 必填，签名
									jsApiList: ["chooseWXPay"] // 必填，需要使用的JS接口列表
								});
								wx.ready(() => {
									wx.checkJsApi({
										jsApiList: ["chooseWXPay"],
										success: function(res) {
											console.log("seccess");
										},
										fail: function(res) {
											console.log(res);
										}
									});
									wx.chooseWXPay({
										timestamp: res.pay
											.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
										nonceStr: res.pay.nonceStr, // 支付签名随机串，不长于 32 位
										package: res.pay
											.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
										signType: res.pay
											.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
										paySign: res.pay.paySign, // 支付签名
										success: function(res) {
											_this.buyShow = false;
											uni.showToast({
												title: "购买成功!"
											})
											setTimeout(() => {
												uni.navigateTo({
													url: "../my/myBox?current=" +
														0 +
														"&status=" + 0
												})
											}, 500)
										},
										fail: function(res) {}
									});
								});
								// wx.error(err => {
								// 	alert(err);
								// });
								// }
							})

						})
					}
				}
				// #endif
			}
		}
	}
</script>

<style lang="less" scoped>
	.payBtn {
		position: fixed;
		z-index: 0;
		bottom: 40rpx;
		left: 50%;
		transform: translateX(-50%);
		display: block;
	}

	.payIcon {
		width: 40rpx;
		height: 40rpx;
	}

	.orderImg {
		width: 185rpx;
		display: block;
		margin: 0 auto;
		height: 185rpx;
	}
</style>
